package handlers

import (
	"strconv"
	"sysu-giep/internal/api/middleware"
	"sysu-giep/internal/database/models"
	"sysu-giep/internal/service"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

var applicationService *service.ApplicationService

// InitApplicationHandlers 初始化申请处理器
func InitApplicationHandlers(as *service.ApplicationService) {
	applicationService = as
}

// GetApplications 获取申请列表
// @Summary 获取申请列表
// @Description 获取申请列表，支持分页和筛选
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param size query int false "每页大小" default(10)
// @Param status query string false "状态"
// @Success 200 {object} response.PageResponse{data=[]map[string]interface{}}
// @Router /applications [get]
func GetApplications(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	status := c.Query("status")
	projectIDStr := c.Query("project_id")
	applicantIDStr := c.Query("applicant_id")

	// 参数验证
	if page < 1 {
		page = 1
	}
	if size < 1 || size > 100 {
		size = 10
	}

	// 解析可选参数
	var projectID *uint
	var applicantID *uint

	if projectIDStr != "" {
		if id, err := strconv.ParseUint(projectIDStr, 10, 32); err == nil {
			pid := uint(id)
			projectID = &pid
		}
	}

	if applicantIDStr != "" {
		if id, err := strconv.ParseUint(applicantIDStr, 10, 32); err == nil {
			aid := uint(id)
			applicantID = &aid
		}
	}

	// 获取申请列表
	applications, total, err := applicationService.GetApplications(page, size, status, projectID, applicantID)
	if err != nil {
		logger.ErrorLog("获取申请列表失败", zap.Error(err))
		response.InternalServerError(c, "获取申请列表失败: "+err.Error())
		return
	}

	response.PageSuccess(c, applications, total, page, size)
}

// GetApplicationByID 根据ID获取申请详情
// @Summary 根据ID获取申请详情
// @Description 根据申请ID获取申请详细信息
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "申请ID"
// @Success 200 {object} response.Response{data=map[string]interface{}}
// @Failure 404 {object} response.Response
// @Router /applications/{id} [get]
func GetApplicationByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的申请ID")
		return
	}

	// 获取申请详情
	application, err := applicationService.GetApplicationByID(id)
	if err != nil {
		logger.ErrorLog("获取申请详情失败", zap.Error(err))
		response.InternalServerError(c, "获取申请详情失败: "+err.Error())
		return
	}

	response.Success(c, application)
}

// CreateApplication 创建申请
// @Summary 创建申请
// @Description 学生、导师创建申请
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body CreateApplicationRequest true "申请信息"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /applications [post]
func CreateApplication(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	var req models.CreateApplicationRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 创建申请
	if err := applicationService.CreateApplication(userID, req); err != nil {
		logger.ErrorLog("创建申请失败", zap.Error(err))
		response.InternalServerError(c, "创建申请失败: "+err.Error())
		return
	}

	response.SuccessWithMessage(c, "申请创建成功", nil)
}

// UpdateApplicationStatus 更新申请状态
// @Summary 更新申请状态
// @Description 企业用户更新申请状态
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "申请ID"
// @Param request body UpdateApplicationStatusRequest true "状态信息"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /applications/{id}/status [put]
func UpdateApplicationStatus(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的申请ID")
		return
	}

	var req models.UpdateApplicationStatusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 更新申请状态
	if err := applicationService.UpdateApplicationStatus(id, userID, req.Status, &userID, req.Feedback); err != nil {
		logger.ErrorLog("更新申请状态失败", zap.Error(err))
		response.InternalServerError(c, err.Error())
		return
	}

	response.SuccessWithMessage(c, "申请状态更新成功", nil)
}

// WithdrawApplication 撤回申请
// @Summary 撤回申请
// @Description 申请人撤回申请
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "申请ID"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /applications/{id} [delete]
func WithdrawApplication(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的申请ID")
		return
	}

	// 撤回申请
	if err := applicationService.WithdrawApplication(id, userID); err != nil {
		logger.ErrorLog("撤回申请失败", zap.Error(err))
		response.InternalServerError(c, "撤回申请失败: "+err.Error())
		return
	}

	response.SuccessWithMessage(c, "申请撤回成功", nil)
}

// GetMyApplications 获取我的申请
// @Summary 获取我的申请
// @Description 获取当前用户的申请列表
// @Tags 申请
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param size query int false "每页大小" default(10)
// @Success 200 {object} response.PageResponse{data=[]map[string]interface{}}
// @Router /applications/my [get]
func GetMyApplications(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))

	// 参数验证
	if page < 1 {
		page = 1
	}
	if size < 1 || size > 100 {
		size = 10
	}

	// 获取我的申请列表
	applications, total, err := applicationService.GetMyApplications(page, size, userID)
	if err != nil {
		logger.ErrorLog("获取我的申请列表失败", zap.Error(err))
		response.InternalServerError(c, "获取我的申请列表失败: "+err.Error())
		return
	}

	response.PageSuccess(c, applications, total, page, size)
}
